﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Xml;
using System.Net;
using System.IO;
using System.Text;

namespace YXShop.Web.admin.product
{
    public partial class taobao_import : System.Web.UI.Page
    {
        private string sip_sessionid = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            if (ChangeHope.WebPage.PageRequest.GetFormString("Option") != string.Empty && ChangeHope.WebPage.PageRequest.GetFormString("idStr") != string.Empty)
            {
                YXShop.Common.PromptInfo.Popedom("001008003", "对不起，您没有删除的权限");
                string types = Request.Form["Option"].Trim();
                string StrID = ChangeHope.WebPage.PageRequest.GetFormString("idStr");
                if (types == "batchImport")
                {
                    string cid = ChangeHope.WebPage.PageRequest.GetFormString("cid");
                    BatchImport(StrID, cid);
                }
                Response.End();
                return;
            }
            if (!IsPostBack)
            {
                if (Session["sip_sessionid"] != null)
                {
                    sip_sessionid = Session["sip_sessionid"].ToString();
                }
                else
                {
                    sip_sessionid = Guid.NewGuid().ToString();
                    Session["sip_sessionid"] = sip_sessionid;
                }
                int pageIndex = ChangeHope.WebPage.PageRequest.GetQueryInt("pageindex");
                if (pageIndex < 0)
                {
                    pageIndex = 1;
                }
                YXShop.Common.SysParameter sp = new YXShop.Common.SysParameter();
                this.txtProductClass.Attributes.Add("readonly", "readonly");
                this.txtProductClass.Attributes.Add("onclick", "selectFile('Random_Productclass',new Array(" + this.hfcid.ClientID + "," + this.txtProductClass.ClientID + "),310,450,'" + sp.DummyPaht + "');");
                TaoBaoStoreProductList(pageIndex);
            }
        }

        #region 列表信息
        protected void TaoBaoStoreProductList(int pageIndex)
        {
            int PageSize = 20;
            ChangeHope.WebPage.Table table = new ChangeHope.WebPage.Table();
            ChangeHope.Common.TaoBaoAPI myapi = new ChangeHope.Common.TaoBaoAPI();
            XmlDocument mydoc = myapi.taobao_items_get("", "iid,title,nick,type,cid,pic_path,delist_time,price,post_fee", pageIndex, PageSize, "成都比威科技有限公司");
            XmlNodeList mylist = mydoc.SelectNodes("rsp/item");
            int num = int.Parse(mydoc.SelectSingleNode("/rsp/totalResults").InnerText);
            table.AddHeadCol("7%", "<input type=\"checkbox\" id=\"chkAll\" onclick=\"CheckAll(this.form)\" alt=\"全选/取消\" />选择");
            table.AddHeadCol("25%", "商品名称");
            table.AddHeadCol("","商品类型");
            table.AddHeadCol("20%", "所属分类");
            table.AddHeadCol("10%", "商品价格");
            table.AddHeadCol("20%", "下架时间");
            table.AddHeadCol("", "操作");
            table.AddRow();
            //添加表的内容
            foreach (XmlNode node in mylist)
            {
                table.AddCol("<input ID=\"cBox\" type=\"checkbox\" value=\"" + node.SelectSingleNode("iid").InnerText + "\" />");
                table.AddCol("<span style='cursor:hand'  onMouseOut=\"hiddenPic();\" onMouseMove=\"showPic('" + node.SelectSingleNode("pic_path").InnerText + "');\">" + node.SelectSingleNode("title").InnerText + "</span>");
                table.AddCol(node.SelectSingleNode("type").InnerText == "fixed"?"一口价":"拍卖");
                table.AddCol(GetItemList_Type(node.SelectSingleNode("cid").InnerText));
                table.AddCol(node.SelectSingleNode("price").InnerText);
                table.AddCol(node.SelectSingleNode("delist_time").InnerText);
                table.AddCol(string.Format("<a href='taobao_info.aspx?productId={0}&nick={1}'>查看</a>", node.SelectSingleNode("iid").InnerText,node.SelectSingleNode("nick").InnerText));
                table.AddRow();
            }
            int pageCount=1;
            pageCount = (num + PageSize - 1) / PageSize;
            StringBuilder shtml = new StringBuilder();
            shtml.Append("<table border='0' height='24px' align='right'>");
            shtml.Append("<tr>");
            shtml.Append("<td>共有" + num + "条商品记录 共分" + pageCount + "页  当前第"+pageIndex+"页</td>");
            shtml.Append("<td>");
            if (pageIndex < 1)
            {
                pageIndex = 1;
            }
            if (pageIndex > pageCount)
            {
                pageIndex = pageCount;
            }
            if (pageIndex <= 1)
            {
                shtml.Append("   <span class=\"disabled\">首页</span>");
                shtml.Append("   <span class=\"disabled\">上一页</span>");
            }
            else
            {
                shtml.Append("   <a href=?pageindex=1>首页</a>");
                shtml.Append("   <a href=?pageindex=" + (pageIndex - 1) + ">上一页</a>");
            }
            if (pageIndex >= pageCount)
            {
                shtml.Append("   <span class=\"disabled\">下一页</span>");
                shtml.Append("   <span class=\"disabled\">尾页</span>");
            }
            else
            {
                shtml.Append("   <a href=?pageindex=" + (pageIndex + 1) + ">下一页</a>");
                shtml.Append("   <a href=?pageindex=" + pageCount + ">尾页</a>");
            }
            shtml.Append("</td>");
            shtml.Append("</tr>");
            shtml.Append("</table>");
            this.lblList.Text = table.GetTable() + shtml.ToString();

        }
        #endregion

        #region 商品类型
        protected string GetItemList_Type(string cid)
        {
            try
            {
                ChangeHope.Common.TaoBaoAPI myapi = new ChangeHope.Common.TaoBaoAPI();
                HttpWebResponse myReponse = myapi.taobao_itemcats_get_v2("", cid, "cid,parent_cid,name");
                StreamReader reader = new StreamReader(myReponse.GetResponseStream(), System.Text.Encoding.UTF8);
                string content = reader.ReadToEnd();
                string sip_status = myReponse.GetResponseHeader("sip_status");
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.LoadXml(content);
                XmlNode url = xmlDoc.SelectSingleNode("//url");
                //根据各自的返回的地址不同值不同
                string sip_redirecturl = "http://localhost:8222/TaoBaoAPITest/OnSaleList.aspx";
                switch (sip_status)
                {
                    case "1004":
                    case "1005":
                        //divMeg.InnerText = content;
                        Response.Redirect(url.InnerText + "&sip_redirecturl=" + sip_redirecturl);

                        break;
                    case "1001":
                    case "9999":
                        XmlNodeList mylist = xmlDoc.SelectNodes("rsp/item_cat");
                        return AddXmlNodesToTable_Type(mylist);
                        break;
                    default:
                        break;
                }
                
            }
            catch(Exception ex)
            {
                ChangeHope.WebPage.BasePage.PageError("链接淘宝服务器出错，返回重新链接。", "taobao_import.aspx");
            }
            return string.Empty;
        }

        private string AddXmlNodesToTable_Type(XmlNodeList nodes)
        {
            foreach (XmlNode node1 in nodes)
            {
                return node1.SelectSingleNode("name").InnerText;
            }
            return string.Empty;
        }
        #endregion

        #region 导数据
        protected void BatchImport(string idStr,string cid)
        {
            string nick = "成都比威科技有限公司";
            string[] productId = idStr.Split(',');
            YXShop.BLL.Product.ProductInfo bll = new YXShop.BLL.Product.ProductInfo();
            YXShop.Model.Product.ProductInfo model = new YXShop.Model.Product.ProductInfo();
            YXShop.BLL.Product.ProductUnit UnitBll = new YXShop.BLL.Product.ProductUnit();
            YXShop.Model.Product.ProductUnit UnitModel = new YXShop.Model.Product.ProductUnit();
            int s = 0;
            ChangeHope.Common.TaoBaoAPI myapi = new ChangeHope.Common.TaoBaoAPI();
            for (int i = 0; i < productId.Length; i++)
            {
                string proId = productId[i];
                HttpWebResponse myReponse = myapi.taobao_items_single_get("iid,num_iid,num,title,nick,type,pic_path,desc,cid,price,type,location.city,list_time ,delist_time,post_fee,valid_thru,modified", proId, nick);
                StreamReader reader = new StreamReader(myReponse.GetResponseStream(), System.Text.Encoding.UTF8);
                string content = reader.ReadToEnd();
                string sip_status = myReponse.GetResponseHeader("sip_status");
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.LoadXml(content);
                if (sip_status == "9999")
                {
                    XmlNodeList mylist = xmlDoc.SelectNodes("rsp/item");
                    foreach (XmlNode node in mylist)
                    {

                        DataTable dt = bll.DTGetListWhere(" and pro_NO='" + node.SelectSingleNode("num_iid").InnerText + "'");
                        if (dt.Rows.Count <=0)
                        {
                            //开始导入信息到数据

                            //如果该单位不存在 就添加一个新的单位
                            string proUnit = "件";
                            if (proUnit != string.Empty)
                            {
                                if (!UnitBll.ExistName(proUnit))
                                {
                                    UnitModel.Name = proUnit;
                                    UnitModel.Sort = 0;
                                    UnitBll.Add(UnitModel);
                                }
                            }

                            #region 加入商品表
                            model.pro_Property = string.Empty;
                            model.pro_CID = cid;
                            model.pro_BrandID = 0;
                            model.pro_Name = node.SelectSingleNode("title").InnerText;
                            //model.pro_Model = string.Empty;
                            model.pro_NO = node.SelectSingleNode("num_iid").InnerText;
                            //model.pro_KeyWord = node.SelectSingleNode("title").InnerText;
                            model.pro_ShopPrice = Convert.ToDecimal(node.SelectSingleNode("price").InnerText);
                            model.pro_MarketPrice = 0;
                            model.pro_RatingDiscount = string.Empty;
                            model.pro_EPoints = 0;
                            model.pro_DonateIntegral = 0;
                            model.pro_Original = node.SelectSingleNode("pic_path").InnerText;
                            model.pro_Images = node.SelectSingleNode("pic_path").InnerText;
                            model.pro_Thumbnail = node.SelectSingleNode("pic_path").InnerText;
                            model.pro_Synopsis = node.SelectSingleNode("desc").InnerText;
                            model.pro_Content = node.SelectSingleNode("desc").InnerText;
                            model.pro_MetaKeywords = node.SelectSingleNode("title").InnerText;
                            model.pro_MetaDescription = node.SelectSingleNode("title").InnerText;
                            model.pro_MetaTitle = node.SelectSingleNode("title").InnerText;
                            model.pro_Weight = 0;
                            model.pro_WeightUnit = 1;//默认为千克                
                            model.pro_Stock = int.Parse(node.SelectSingleNode("num").InnerText);
                            model.pro_Unit = proUnit;
                            model.pro_Alarm = 0;
                            model.pro_AuditCount = 0;
                            model.pro_Audit = 0;//默认为下架 因为批量导入的不是完整信息
                            model.pro_State = "0|0|0|0|0|0|";
                            if (node.SelectSingleNode("type").InnerText == "fixed")
                            {
                                model.pro_Designation = "1|0|0|0|0|";
                            }
                            else
                            {
                                model.pro_Designation = "0|0|1|0|0|";
                            }
                            model.pro_RelatingArtID = "0";
                            model.pro_RelatingproID = "0";
                            model.pro_CreateTime = Convert.ToDateTime(node.SelectSingleNode("modified").InnerText);
                            model.pro_UpdateTime = Convert.ToDateTime(node.SelectSingleNode("modified").InnerText);
                            model.pro_OnClicks = 0;
                            model.pro_IsAllowComment = 1;
                            model.pro_SaleNum = 0;
                            model.pro_CostPrice = 0;
                            model.pro_AutoUp = Convert.ToDateTime(node.SelectSingleNode("list_time").InnerText);
                            model.pro_AutoDown = Convert.ToDateTime(node.SelectSingleNode("delist_time").InnerText);
                            model.pro_IsAuto = 0;
                            model.pro_SaleType = 1;
                            model.pro_IntegralPrice = 0;
                            model.pro_Area = "0";
                            model.pro_PutoutID = 0;
                            model.pro_PutoutType = 0;
                            model.pro_Templates = "";
                            if (bll.Add(model) != 0)
                            {
                                s++;
                            }
                            #endregion
                        }
                    }
                }

            }
           Response.Write("成功将淘宝数据导进商城共"+s+"条");

        }
        #endregion
    }
}
